package com.isoft.game.common.controller;

import org.springframework.web.bind.annotation.ModelAttribute;

import com.isoft.game.common.component.PageUtil;
import com.isoft.game.common.model.CommonPageGridModel;
import com.isoft.game.common.model.GridModel;

import javax.servlet.http.HttpServletRequest;

/**
 * Created with family.
 * author: cy
 * Date: 16/6/16
 * Time: 上午10:52
 * description: 分页初始化
 */

public class PaginationController<T> extends ResponseController {

    protected static final String PAGINATIONKEY = "pagination";

    public PaginationController() {
    }

    public PageUtil<T> getPaginationUtility() {
        PageUtil paginationUtility = (PageUtil)request.getAttribute(PAGINATIONKEY);
        if(paginationUtility == null) {
            throw new NullPointerException("未传递分页参数（page&rows），却在方法中使用paginationUtility对象。");
        } else {
            return paginationUtility;
        }
    }

    @ModelAttribute
    private void setPagnationAttribute(HttpServletRequest request, Integer rows, Integer page, String sort, String order) {
        PageUtil _paginationUtility;
        if(rows != null && page != null && sort != null && order != null) {
            _paginationUtility = new PageUtil();
            _paginationUtility.setPageNum(page.intValue());
            _paginationUtility.setPageSize(rows.intValue());
            _paginationUtility.setOrderBy(sort + " " + order);
            request.setAttribute(PAGINATIONKEY, _paginationUtility);
        }

        else if(rows != null && page != null) {
            _paginationUtility = new PageUtil();
            _paginationUtility.setPageNum(page.intValue());
            _paginationUtility.setPageSize(rows.intValue());
            request.setAttribute(PAGINATIONKEY, _paginationUtility);
        } else if(sort != null && order != null) {
            _paginationUtility = new PageUtil();
            _paginationUtility.setOrderBy(sort + " " + order);
            request.setAttribute(PAGINATIONKEY, _paginationUtility);
        }

    }

    /**
     * get gridMoel
     * @return
     */
    public GridModel getGridModelResponse(){
        PageUtil pagination = getPaginationUtility();
        if(null != getPaginationUtility())
            return pagination.getGridModel();
        else{
            return new CommonPageGridModel();
        }
    }
}
